package com.fuershiye.woman.monitor.dao;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fuershiye.woman.monitor.model.Unit;

@Repository("unitDao")
@SuppressWarnings("unchecked")
public class UnitDao {

    @Autowired
    private HibernateDao hibernateDao;

    public void save(Unit unit){
        hibernateDao.save(unit);
    }

    @SuppressWarnings("unchecked")
	public List<Unit> list(String name, Integer status) {

        StringBuffer sb = new StringBuffer("from Unit where 1=1 ");
        if(status!=null&&status==1){
        	sb.append("and status=1 ");
        }
        if(StringUtils.isNotBlank(name)){
        	sb.append("and name like:name ");
    	}
        
        Query query = hibernateDao.getQuery(sb.toString());
        
        if(StringUtils.isNotBlank(name)){
            query.setString("name","%" + name + "%");
    	}
        return query.list();
    }

    public Unit get(Long id) {
        return hibernateDao.getById(Unit.class,id);
    }

    public void delete(Long id) {
        String sql = "update Unit set status = 0 where id = ?";
        SQLQuery query = hibernateDao.getSqlQuery(sql).addEntity(Unit.class);
        query.setLong(0, id);
        query.executeUpdate();
    }
    
}
